/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief This is a example for using the Ranging interface.
 * \author Antti Maula <antti.maula@tkk.fi>
 */
#include "RangingClient.hpp"
#include "ownutils.h"

//*****************************************************************************
#define GIMI_CLIENT_API 20000
#include "gimi.h"
//*****************************************************************************

//*****************************************************************************
static int verbose = ODINFO;
static gimi::GIMI g;
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;

static ownMutexHandle activeInterfacesMutex = ownMutex_Init();
static std::set<MaCI::CMaCI *> activeInterfaces;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tRangingClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tSpecify the data source\n");
  fprintf(stderr,"  \t\t\t\tOR\n");
  fprintf(stderr,"  [-S name]\t\t\tSpecify the data source by MaCISL\n");


  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      dPrint(1,"Terminating...");
      run = false;
      ownMutex_Lock(activeInterfacesMutex);
      for(EACH_IN_i(activeInterfaces)) {
        (*i)->Close();
      }
      activeInterfaces.clear();
      ownMutex_Unlock(activeInterfacesMutex);

      g.stop();
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName = "";
  std::string gimnetSourceName = "";
  std::string datasourceMaCISL;
  
  // Objects
  MaCI::Ranging::CRangingClient rc(&g, 0); 

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(verbose);
  debugSetLogFilename("RangingClientExample.log");


  InitSignalHandler();

  // Greet
  fprintf(stderr,
          "\n%s\n", argv[0]);

  // Parse parameters
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "S:s:n:u:p:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////
      ///// GIMnet parameters /////////
      /////////////////////////////////
    case 's':
      gimnetSourceName = optarg;
      dPrint(3,"Using GIMnet source name '%s'", optarg);
      break;

    case 'S':
      datasourceMaCISL = optarg;
      dPrint(3,"Using DataSource MaCISL '%s'", optarg);
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
        debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  MaCI::EMaCIError e;
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(ODERROR,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
           gimnetAP.c_str(), 
           gimnetAPPort, 
           gimnetName.size()?gimnetName.c_str():"<anonymous>",
           gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(ODINFO,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
           gimnetAP.c_str(), 
           gimnetAPPort, 
           gimnetName.size()?gimnetName.c_str():"<anonymous>",
           gimi::getGimiErrorString(r).c_str());


    // Set target
    if (gimnetSourceName.size()) {
      rc.SetDefaultTarget(gimnetSourceName);
      
    } else {
      // GIMI is Open(), so we can execute this.
      dPrint(ODINFO,"Attempting to set the target using MaCISL - this may take up to 3000ms to complete.");
      rc.SetDefaultTarget(MaCI::MaCICtrl::SMaCISL(datasourceMaCISL), 3000);
      
    }
    
    
    // Attempt to Open Client
    if ( (e = rc.Open()) != MaCI::KMaCIOK) {
      dPrint(ODERROR,"Failed to Open RangingClient instance! (%s)",
             GetErrorStr(e).c_str());
      
    } else {
      int index = -1;
      MaCI::Common::TTimestamp timestamp;
      MaCI::Ranging::TDistanceHeader header;
      MaCI::Ranging::TDistanceArray array;
      MaCI::Ranging::TDeviceInformationLimits limits;
      MaCI::Ranging::TDeviceInformationPosition pose;

      bool gr;
 
      // Call for Pose. Will be slow on first call, but then returns cached info.
      dPrint(ODINFO,"Requesting pose...('Direct' flag unset)");
      gr = rc.GetDevicePosition(pose, 1000, false);
      if (gr) {
        dPrint(ODINFO,"Ranging Device at (%.2f, %.2f, %.2f) pointing at %.3f rad", 
               pose.x, pose.y, pose.z, pose.heading);
        
      } else {
        dPrintLCRed(ODINFO, "Pose request FAILED!");
        
      }
      
      // Call for limits. Will be slow on first call, but then returns cached info.
      dPrint(ODINFO,"Requesting limits...('Direct' flag unset)");
      gr = rc.GetDeviceLimits(limits, 1000, false);
      if (gr) {
        dPrint(ODINFO,"Ranging device limits: Min:%.3f max:%.3f", 
               limits.min_distance, limits.max_distance);
      } else {
        dPrintLCRed(ODINFO, "Limits request FAILED!");
        
      }
      
      while(run) {
        dPrint(ODVINFO,"Requesting array...");
        gr = rc.GetDistanceArray(array, &header, &timestamp, &index, 1000);
        if (gr) {
          dPrint(ODINFO,"Got array... (Contains %d Distances)", header.beam_count);
          for(EACH_IN_i(array)) {
            dPrint(ODVINFO+1,"Distance: %fm @ %frad", 
                   i->distance, i->angle); 
          }
        }
      }
    }
  }
  
  return 0;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

